var Promise = require('bluebird');

var mongoBase = require('../common/mongo-base');
var page = require('../common/page');
var utils = require('../common/utils');

module.exports = {
  newsSearch: newsSearch,
  planeSearch: planeSearch
};

function newsSearch(req, res, next) {

  var keyword = req.query.keyword;
  var pageNo = Math.floor(req.query.pageNo);
  var pageSize = Math.floor(req.query.pageSize);
  pageNo = pageNo ? pageNo: 1;
  pageSize = pageSize ? pageSize: 10;

  if (!keyword) {
    res.redirect('/news/list');
    return;
  };

  var query = {
    "$or": [{"artibodyTitle": new RegExp(keyword)}, {"keywords": new RegExp(keyword)}, {"artibody": new RegExp(keyword)}]
  };
  var fields = {_id:1, originalLink:1, artibodyTitle:1, mediaName:1, pubDate:1, medialink:1, photo:1, ellipsis:1, pubDate:1};
  var options = {sort:{date:-1}};

  mongoBase.findData('news-article', query, fields, options)

    .then(function(data) {

      var newsList = utils.getSearchlist(data, pageNo, pageSize);

      var resData = {
        isNews: true,
        searchType: 'news',
        keyword: keyword,
        newsList: newsList,
        totalCount: data.length
      }
      /*分页数据*/
      resData.page = page.getPage(pageNo, pageSize, resData.totalCount, 7);
      res.render('news', resData);
    })

    .catch(function(err){
      console.log(err);
    });
}


function planeSearch(req, res, next) {

  var keyword = req.query.keyword;
  var pageNo = Math.floor(req.query.pageNo);
  var pageSize = Math.floor(req.query.pageSize);
  pageNo = pageNo ? pageNo: 1;
  pageSize = pageSize ? pageSize: 10;

  if (!keyword) {
    res.redirect('/plane/list');
    return;
  };

  var query = {
    "$or": [{"planeName": new RegExp(keyword)}, {"ellipsis": new RegExp(keyword)}, {"parameters.value": new RegExp(keyword)}, {"others.name": new RegExp(keyword)}, {"others.description": new RegExp(keyword)}]
  };
  var fields = {_id:1, planeName:1, photos:1, parameters:1};
  var options = {sort:{date:-1}};

  mongoBase.findData('plane-data', query, fields, options)

    .then(function(data) {

      var planeList = utils.getSearchlist(data, pageNo, pageSize);

      var resData = {
        isPlane: true,
        searchType: 'plane',
        keyword: keyword,
        planeList: planeList,
        totalCount: data.length
      }
      /*分页数据*/
      resData.page = page.getPage(pageNo, pageSize, resData.totalCount, 7);
      res.render('plane', resData);
    })

    .catch(function(err){
      console.log(err);
    });
}

